import numpy as  np
from sklearn.neighbors import KNeighborsClassifier

train_x = [[0,0],[2,3],[1,1],[2,2],[5,5],[6,7],[6,6],[4,5]]
train_y = ['A','A','A','A','B','B','B','B']
x = [[0,1],[2,0]]
k = 2

def knn1(x,train_x,train_y,k):
    train_x = np.array(train_x)
    x = np.array(x)
    knn_clf = KNeighborsClassifier(n_neighbors=k)    #分类器
    knn_clf.fit(train_x, train_y)                    #进行拟合
    print("测试准确度：%f"%(knn_clf.score(train_x, train_y)))
    print("预测结果：%s"%(knn_clf.predict(x)))

def knn2(x,train_x,train_y):
    train_x = np.array(train_x)
    x = np.array(x)
    best_score = 0
    for i in range(len(train_x[0])): #归一化
        if np.max(train_x[i]) - np.min(train_x[i]) == 0:
            train_x[i] = 0
        else :
            train_x[i] = (train_x[i] - np.min(train_x[i])) / (np.max(train_x[i]) - np.min(train_x[i]))
    for method in ["uniform", "distance"]:
        for k in range(1, 3):
            for p in range(1, 6):
                knn_clf = KNeighborsClassifier(n_neighbors=k, weights=method, p=p)
                knn_clf.fit(train_x, train_y)
                score = knn_clf.score(train_x, train_y)
                if score > best_score:
                    best_k = k
                    best_score = score
                    best_p = p
                    best_method = method                   #进行拟合
    print("最优k值%d"%(best_k))
    print("最优权重方法%s" % (best_method))
    print("最优p值%d" % (best_p))
    print("测试准确度：%f"%(best_score))
    print("预测结果：%s"%(knn_clf.predict(x)))

if __name__== "__main__":
    knn2(x,train_x,train_y)
'''
    测试准确度：1.000000
    预测结果：['A' 'A']
'''
'''
最优k值1
最优权重方法uniform
最优p值1
测试准确度：1.000000
预测结果：['A' 'A']
'''